﻿@page "/register"
@using System.ComponentModel.DataAnnotations
@inject NavigationManager NavigationManager
@inject IHttpClientFactory HttpClientFactory
@inject IJSRuntime JSRuntime

<div class="register-container">
    <div class="register-box">
        <div class="logo">
            <img src="/logo.png" alt="Logo" class="logo-image" />
        </div>
        <h2 class="register-title">用户注册</h2>

        <EditForm Model="@registerForm" OnValidSubmit="HandleRegister">
            <DataAnnotationsValidator />
            <ValidationSummary />

            <div class="form-group">
                <label for="username">用户名</label>
                <InputText @bind-Value="registerForm.Username" id="username" class="form-control custom-input" placeholder="请输入用户名" />
                <ValidationMessage For="@(() => registerForm.Username)" />
            </div>

            <div class="form-group">
                <label for="email">邮箱</label>
                <InputText @bind-Value="registerForm.Email" id="email" class="form-control custom-input" placeholder="请输入邮箱" />
                <ValidationMessage For="@(() => registerForm.Email)" />
            </div>

            <div class="form-group">
                <label for="password">密码</label>
                <InputText @bind-Value="registerForm.Password" id="password" type="password" class="form-control custom-input" placeholder="请输入密码" />
                <ValidationMessage For="@(() => registerForm.Password)" />
            </div>

            <div class="form-group">
                <label for="confirmPassword">确认密码</label>
                <InputText @bind-Value="registerForm.ConfirmPassword" id="confirmPassword" type="password" class="form-control custom-input" placeholder="请再次输入密码" />
                <ValidationMessage For="@(() => registerForm.ConfirmPassword)" />
            </div>

            <div class="form-group">
                <label for="role">选择角色</label>
                <InputSelect @bind-Value="registerForm.Role" id="role" class="form-control role-select">
                    <option value="farmer">农民</option>
                    <option value="consumer">消费者</option>
                </InputSelect>
                <ValidationMessage For="@(() => registerForm.Role)" />
            </div>

            <div class="form-group">
                <button type="submit" class="btn btn-primary register-btn" disabled="@loading">
                    @if (loading)
                    {
                        <span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>
                        <span>注册中...</span>
                    }
                    else
                    {
                        <span>注册</span>
                    }
                </button>
            </div>

            <div class="login-link">
                <span>已有账号？</span>
                <a href="/login" class="login-link-text">返回登录</a>
            </div>
        </EditForm>
    </div>
</div>

@code {
    private RegisterModel registerForm = new RegisterModel();
    private bool loading = false;

    public class RegisterModel
    {
        [Required(ErrorMessage = "请输入用户名")]
        [MinLength(3, ErrorMessage = "用户名长度不能少于3位")]
        public string Username { get; set; }

        [Required(ErrorMessage = "请输入邮箱")]
        [EmailAddress(ErrorMessage = "请输入有效的邮箱地址")]
        public string Email { get; set; }

        [Required(ErrorMessage = "请输入密码")]
        [MinLength(6, ErrorMessage = "密码长度不能少于6位")]
        public string Password { get; set; }

        [Required(ErrorMessage = "请再次输入密码")]
        [CustomValidation(typeof(RegisterModel), "ValidateConfirmPassword")]
        public string ConfirmPassword { get; set; }

        [Required(ErrorMessage = "请选择角色")]
        public string Role { get; set; } = "farmer";

        public static ValidationResult ValidateConfirmPassword(string confirmPassword, ValidationContext context)
        {
            var model = (RegisterModel)context.ObjectInstance;
            return confirmPassword == model.Password
                ? ValidationResult.Success
                : new ValidationResult("两次输入的密码不一致");
        }
    }

    private async Task HandleRegister()
    {
        loading = true;


        try
        {
            var httpClient = HttpClientFactory.CreateClient("Api");

            // 1. 调用注册接口
            var response = await httpClient.PostAsJsonAsync("/api/user/register", new
            {
                username = registerForm.Username,
                password = registerForm.Password,
                email = registerForm.Email,
                role = registerForm.Role
            });

            var registerResponseContent = await response.Content.ReadAsStringAsync();
            Console.WriteLine($"Register API 返回: {registerResponseContent}");

            if (response.IsSuccessStatusCode)
            {
                var result = await response.Content.ReadFromJsonAsync<RegisterResponse>();

                if (result?.Success == true)
                {
                    await JSRuntime.InvokeVoidAsync("alert", "注册成功！");
                    NavigationManager.NavigateTo("/login");
                }
            }
            else
            {
                var errorResponse = await response.Content.ReadFromJsonAsync<ErrorResponse>();
                var errorMessage = response.StatusCode switch
                {
                    System.Net.HttpStatusCode.BadRequest =>
                        errorResponse?.Message?.Contains("用户名已存在") == true
                            ? "用户名已存在"
                            : errorResponse?.Message?.Contains("邮箱已被注册") == true
                                ? "邮箱已被注册"
                                : "请检查输入信息是否正确",
                    System.Net.HttpStatusCode.InternalServerError => "服务器错误，请稍后重试",
                    _ => "注册失败，请稍后重试"
                };

                await JSRuntime.InvokeVoidAsync("alert", errorMessage);
            }
        }
        catch (Exception ex)
        {
            await JSRuntime.InvokeVoidAsync("alert", "网络错误，请检查网络连接");
            Console.WriteLine(ex.Message);
        }
        finally
        {
            loading = false;
        }
    }

    public class RegisterResponse
    {
        public bool Success { get; set; }
    }

    public class ErrorResponse
    {
        public string Message { get; set; }
    }
}

<style>
    .register-container {
        min-height: 100vh;
        display: flex;
        justify-content: center;
        align-items: center;
        padding: 20px;
        background-color: #f0f2f5;
        background-image: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    }

    .register-box {
        width: 100%;
        max-width: 450px;
        padding: 30px;
        border-radius: 12px;
        box-shadow: 0 6px 20px rgba(0, 0, 0, 0.1);
        border: none;
        background-color: rgba(255, 255, 255, 0.95);
    }

    .logo {
        text-align: center;
        margin-bottom: 20px;
    }

    .logo-image {
        height: 70px;
        width: auto;
        max-width: 100%;
        object-fit: contain;
        border-radius: 40px;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    }

    .register-title {
        text-align: center;
        color: #2c3e50;
        margin-bottom: 30px;
        font-weight: 600;
        font-size: 22px;
        letter-spacing: 0.5px;
    }

    .form-group {
        margin-bottom: 20px;
    }

        .form-group label {
            display: block;
            margin-bottom: 8px;
            color: #606266;
            font-size: 14px;
        }

    .custom-input {
        border-radius: 8px;
        height: 44px;
        line-height: 44px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
        width: 100%;
    }

        .custom-input:focus {
            border-color: #409eff;
            outline: none;
        }

    .role-select {
        width: 100%;
        height: 44px;
        border-radius: 8px;
        padding: 0 15px;
        border: 1px solid #dcdfe6;
    }

    .register-btn {
        width: 100%;
        margin-top: 10px;
        height: 44px;
        font-size: 16px;
        border-radius: 8px;
        background-color: #409eff;
        border-color: #409eff;
        transition: all 0.3s;
        color: white;
        border: none;
        cursor: pointer;
    }

        .register-btn:hover {
            background-color: #66b1ff;
            border-color: #66b1ff;
            transform: translateY(-2px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        }

        .register-btn:disabled {
            background-color: #a0cfff;
            cursor: not-allowed;
        }

    .login-link {
        margin-top: 20px;
        text-align: center;
        font-size: 14px;
        color: #666;
    }

    .login-link-text {
        color: #409eff;
        margin-left: 5px;
        text-decoration: none;
    }

        .login-link-text:hover {
            color: #66b1ff;
            text-decoration: underline;
        }
</style>